import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/utils/text_filed_utils.dart';
import 'package:kq_flutter_core_widget/widgets/shadow/kq_box_decoration.dart';
import 'package:kq_flutter_core_widget/widgets/shadow/kq_box_shadow.dart';

import '../../resources/kq_pad_theme_colors.dart';
import '../../resources/l10n/kq_pad_intl.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_pad_divider.dart';
import '../textFiled/kq_pad_textfiled.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 输入上下限组件
///
/// [ItemType.editUpperLower]
///
/// @author 高裕
///
/// 结合 KqPadFormEntity 使用
class KqPadEditUpperLowerItemView extends StatefulWidget {
  /// 通用属性
  final KqPadFormEntity entity;

  const KqPadEditUpperLowerItemView({Key? key, required this.entity})
      : super(key: key);

  @override
  KqPadEditUpperLowerItemViewState createState() =>
      KqPadEditUpperLowerItemViewState();
}

class KqPadEditUpperLowerItemViewState
    extends State<KqPadEditUpperLowerItemView> {
  @override
  void initState() {
    widget.entity.widgetState = this;
    widget.entity.valuesForShow ??= [null, null];
    widget.entity.valuesForSubmit ??= [null, null];
    if (widget.entity.controllers != null &&
        widget.entity.valuesForShow != null) {
      if (widget.entity.controllers![1] != null &&
          widget.entity.valuesForShow![1] != null) {
        TextFiledUtil.setValue(
            widget.entity.controllers![1]!, widget.entity.valuesForShow![1]!);
      }
      if (widget.entity.controllers![2] != null &&
          widget.entity.valuesForShow![2] != null) {
        TextFiledUtil.setValue(
            widget.entity.controllers![2]!, widget.entity.valuesForShow![2]!);
      }
    }
    calTitleWidth();
    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY = scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  double titleWidth = 0;

  calTitleWidth() {
    // 计算标题宽度
    TextStyle titleStyle = widget.entity.titleStyle ??
        TextStyle(
            fontSize: widget.entity.titleFontSize ??
                KqPadThemeManager.instance
                    .getConfig()
                    .formConfig
                    .titleFontSize ??
                7.dm,
            color: widget.entity.titleColor ?? KqPadThemeColors.text26);

    String titleWidthString = "";
    for (int i = 0; i < (widget.entity.titleFixedWidthCharCount ?? 8); i++) {
      titleWidthString += "中";
    }
    if ((widget.entity.titleandMustOverAll != null &&
            widget.entity.titleandMustOverAll!) ||
        KqPadThemeManager.instance.getConfig().formConfig.titleandMustOverAll) {
      titleWidthString = '* $titleWidthString';
    }
    titleWidth = measureTextWidth(titleWidthString, textStyle: titleStyle);
    if (kIsWeb) {
      double fontSize = widget.entity.titleFontSize ??
          KqPadThemeManager.instance.getConfig().formConfig.titleFontSize ??
          7.dm;
      double width = (widget.entity.titleFixedWidthCharCount ?? 8) * fontSize;
      if (titleWidth < width) {
        titleWidth = width; // 最小宽度
      }
    }
  }

  @override
  void didUpdateWidget(covariant KqPadEditUpperLowerItemView oldWidget) {
    widget.entity.widgetState = this;
    widget.entity.valuesForShow ??= [null, null];
    widget.entity.valuesForSubmit ??= [null, null];
    if (widget.entity.controllers != null &&
        widget.entity.valuesForShow != null) {
      if (widget.entity.controllers![1] != null &&
          widget.entity.valuesForShow![1] != null) {
        TextFiledUtil.setValue(
            widget.entity.controllers![1]!, widget.entity.valuesForShow![1]!);
      }
      if (widget.entity.controllers![2] != null &&
          widget.entity.valuesForShow![2] != null) {
        TextFiledUtil.setValue(
            widget.entity.controllers![2]!, widget.entity.valuesForShow![2]!);
      }
    }
    calTitleWidth();
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    widget.entity.valuesForSubmit = widget.entity.valuesForShow;
    widget.entity.valuesForShow ??= [null, null];
    widget.entity.valuesForSubmit ??= [null, null];
    // 背景颜色
    var bgColor = widget.entity.backgroundColor;

    // 计算标题宽度
    TextStyle titleStyle = widget.entity.titleStyle ??
        TextStyle(
            fontSize: widget.entity.titleFontSize ??
                KqPadThemeManager.instance
                    .getConfig()
                    .formConfig
                    .titleFontSize ??
                7.dm,
            color: widget.entity.titleColor ?? KqPadThemeColors.text26);

    bool isHideInputBox = (widget.entity.isHideInputBox != null &&
            widget.entity.isHideInputBox!) ||
        (KqPadThemeManager.instance.getConfig().formConfig.isHideInputBox !=
                null &&
            KqPadThemeManager.instance.getConfig().formConfig.isHideInputBox!);
    // isHideInputBox = true;
    return Visibility(
      visible: widget.entity.visible,
      child: Column(
        children: [
          Container(
            color: bgColor,
            padding: EdgeInsets.only(
                right: widget.entity.paddingHorizontal ??
                    KqPadThemeManager.instance
                        .getConfig()
                        .formConfig
                        .paddingHorizontal ??
                    8.dm,
                top: widget.entity.paddingVertical ?? 0,
                bottom: widget.entity.paddingVertical ?? 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  crossAxisAlignment: widget.entity.multiline
                      ? CrossAxisAlignment.baseline
                      : CrossAxisAlignment.center,
                  textBaseline:
                      widget.entity.multiline ? TextBaseline.alphabetic : null,
                  children: <Widget>[
                    /// 是否必填
                    _buildMustSign(),
                    // 标题
                    Container(
                      width: titleWidth + (isHideInputBox ? 0 : 6.dm),
                      padding: EdgeInsets.only(
                          right: isHideInputBox ? 0 : 6.dm, top: 0.5.dm),
                      alignment: Alignment.centerRight,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          /// 左边自定义控件
                          /// 自定义布局，来自实体类
                          widget.entity.customLeftView != null
                              ? widget.entity.customLeftView!(widget.entity)
                              : Container(),
                          _buildOverAllTitle(titleStyle),
                          _buildTitle(titleStyle)
                        ],
                      ),
                    ),
                    Expanded(
                      /// 输入框
                      child: Container(
                        height: widget.entity.isEditable() &&
                                !widget.entity.multiline
                            ? KqPadThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .height ??
                                20.dm
                            : null,
                        constraints: BoxConstraints(
                            minHeight: KqPadThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .height ??
                                20.dm),
                        padding: widget.entity.isEditable()
                            ? EdgeInsets.only(top: 0.5.dm, left: 6.dm)
                            : EdgeInsets.symmetric(vertical: 7.dm),
                        margin: widget.entity.isEditable()
                            ? EdgeInsets.only(top: 2.dm, bottom: 2.dm)
                            : null,
                        decoration:
                            widget.entity.isEditable() && !isHideInputBox
                                ? KqBoxDecoration(
                                    boxShadow: KqPadThemeManager.instance
                                                .getConfig()
                                                .formConfig
                                                .boderColor !=
                                            null
                                        ? null
                                        : [
                                            KqBoxShadow(
                                                offset: Offset(0.5.dm, 0.5.dm),
                                                blurRadius: 0,
                                                spreadRadius: 0,
                                                color: const Color(0x80FFFFFF)),
                                            KqBoxShadow(
                                                offset: Offset(0, 0.5.dm),
                                                blurRadius: 3.dm,
                                                spreadRadius: 0,
                                                inset: true,
                                                color: const Color(0xFFB2B7CE)),
                                            KqBoxShadow(
                                                offset: Offset(0.5.dm, 0.5.dm),
                                                blurRadius: 0.5.dm,
                                                spreadRadius: 0,
                                                inset: true,
                                                color: const Color(0xFFC9CCD9)),
                                          ],
                                    borderRadius: BorderRadius.circular(
                                        KqPadThemeManager.instance
                                                .getConfig()
                                                .formConfig
                                                .radius ??
                                            1.dm),
                                    border: Border.all(
                                        color: KqPadThemeManager.instance
                                                .getConfig()
                                                .formConfig
                                                .boderColor ??
                                            KqPadThemeColors.bgTransparent),
                                    color: isHideInputBox
                                        ? KqPadThemeColors.bgTransparent
                                        : KqPadThemeColors.bgWhite,
                                  )
                                : null,
                        child: Row(
                          children: [
                            Expanded(
                              child: Row(
                                mainAxisAlignment: isHideInputBox
                                    ? MainAxisAlignment.end
                                    : MainAxisAlignment.start,
                                children: [
                                  if (widget.entity.isEditable())
                                    Expanded(
                                        child: SizedBox(
                                            width: leftTextFiledWidth(widget
                                                .entity.valuesForShow?[0]),
                                            child: KqPadTextFiled(
                                              multiline:
                                                  widget.entity.multiline,
                                              maxLines: 1,
                                              showShadow: false,
                                              inputType:
                                                  widget.entity.inputType,
                                              editable:
                                                  widget.entity.isEditable(),
                                              forceShowPlaceHolder: widget
                                                  .entity.forceShowPlaceHolder,
                                              controller:
                                                  widget.entity.controllers?[0],
                                              textColor:
                                                  widget.entity.contentColor,
                                              fontSize: widget
                                                      .entity.contentFontSize ??
                                                  KqPadThemeManager.instance
                                                      .getConfig()
                                                      .formConfig
                                                      .contentFontSize,
                                              enableClearButton: widget
                                                  .entity.enableClearButton,
                                              textAlign: isHideInputBox
                                                  ? TextAlign.end
                                                  : TextAlign.start,
                                              newValue: widget.entity
                                                      .valuesForShow?[0] ??
                                                  '',
                                              placeHolder: widget.entity.hint,
                                              maxCharCount:
                                                  widget.entity.maxCharCount,
                                              inputFormatters:
                                                  widget.entity.inputFormatters,
                                              onFocusChanged: (hasFocus) {
                                                widget.entity
                                                    .onFocusChangedWidthIndex
                                                    ?.call(hasFocus, 0);
                                              },
                                              onMonitor: (str) {
                                                widget
                                                    .entity.onMonitorWidthIndex
                                                    ?.call(
                                                        widget.entity, str, 0);
                                              },
                                              onChanged: (text) {
                                                widget.entity
                                                    .valuesForShow?[0] = text;
                                                widget.entity
                                                    .valuesForSubmit?[0] = text;
                                                widget
                                                    .entity.onChangedWidthIndex
                                                    ?.call(text, 0);
                                              },
                                            ))),
                                  if (widget.entity.isEditable())
                                    SizedBox(
                                      width: 8.dm,
                                    ),
                                  if (widget.entity.isEditable())
                                    Text(
                                      "~",
                                      style: TextStyle(
                                        fontSize: 12.dm,
                                        color: KqPadThemeManager.instance
                                                .getConfig()
                                                .formConfig
                                                .upperLowerColor ??
                                            KqPadThemeColors.textBF,
                                      ),
                                    ),
                                  if (widget.entity.isEditable())
                                    SizedBox(
                                      width: 8.dm,
                                    ),
                                  if (widget.entity.isEditable())
                                    isHideInputBox
                                        ? Expanded(
                                            child: SizedBox(
                                            width: leftTextFiledWidth(widget
                                                .entity.valuesForShow?[1]),
                                            child: KqPadTextFiled(
                                              multiline:
                                                  widget.entity.multiline,
                                              maxLines: 1,
                                              inputType:
                                                  widget.entity.inputType,
                                              editable:
                                                  widget.entity.isEditable(),
                                              forceShowPlaceHolder: widget
                                                  .entity.forceShowPlaceHolder,
                                              controller:
                                                  widget.entity.controllers?[1],
                                              textColor:
                                                  widget.entity.contentColor,
                                              fontSize: widget
                                                      .entity.contentFontSize ??
                                                  KqPadThemeManager.instance
                                                      .getConfig()
                                                      .formConfig
                                                      .contentFontSize,
                                              enableClearButton: widget
                                                  .entity.enableClearButton,
                                              textAlign: TextAlign.end,
                                              newValue: widget.entity
                                                      .valuesForShow?[1] ??
                                                  '',
                                              placeHolder: widget.entity.hint,
                                              maxCharCount:
                                                  widget.entity.maxCharCount,
                                              inputFormatters:
                                                  widget.entity.inputFormatters,
                                              onFocusChanged: (hasFocus) {
                                                widget.entity
                                                    .onFocusChangedWidthIndex
                                                    ?.call(hasFocus, 1);
                                              },
                                              onMonitor: (str) {
                                                widget
                                                    .entity.onMonitorWidthIndex
                                                    ?.call(
                                                        widget.entity, str, 1);
                                              },
                                              showShadow: false,
                                              onChanged: (text) {
                                                widget.entity
                                                    .valuesForShow?[1] = text;
                                                widget.entity
                                                    .valuesForSubmit?[1] = text;
                                                update();
                                                widget
                                                    .entity.onChangedWidthIndex
                                                    ?.call(text, 1);
                                              },
                                            ),
                                          ))
                                        : Expanded(
                                            child: KqPadTextFiled(
                                              multiline:
                                                  widget.entity.multiline,
                                              maxLines: 1,
                                              inputType:
                                                  widget.entity.inputType,
                                              editable:
                                                  widget.entity.isEditable(),
                                              forceShowPlaceHolder: widget
                                                  .entity.forceShowPlaceHolder,
                                              controller:
                                                  widget.entity.controllers?[1],
                                              textColor:
                                                  widget.entity.contentColor,
                                              fontSize: widget
                                                      .entity.contentFontSize ??
                                                  KqPadThemeManager.instance
                                                      .getConfig()
                                                      .formConfig
                                                      .contentFontSize,
                                              enableClearButton: widget
                                                  .entity.enableClearButton,
                                              textAlign: TextAlign.start,
                                              newValue: widget.entity
                                                      .valuesForShow?[1] ??
                                                  '',
                                              placeHolder: widget.entity.hint,
                                              maxCharCount:
                                                  widget.entity.maxCharCount,
                                              inputFormatters:
                                                  widget.entity.inputFormatters,
                                              onFocusChanged: (hasFocus) {
                                                widget.entity
                                                    .onFocusChangedWidthIndex
                                                    ?.call(hasFocus, 1);
                                              },
                                              onMonitor: (str) {
                                                widget
                                                    .entity.onMonitorWidthIndex
                                                    ?.call(
                                                        widget.entity, str, 1);
                                              },
                                              showShadow: false,
                                              onChanged: (text) {
                                                widget.entity
                                                    .valuesForShow?[1] = text;
                                                widget.entity
                                                    .valuesForSubmit?[1] = text;
                                                update();
                                                widget
                                                    .entity.onChangedWidthIndex
                                                    ?.call(text, 1);
                                              },
                                            ),
                                          ),

                                  if (!widget.entity.isEditable())
                                    Expanded(
                                      child: Text(
                                        '${widget.entity.valuesForShow?[0] ?? ''}～${widget.entity.valuesForShow?[1] ?? ''}',
                                        textAlign: TextAlign.end,
                                        style: TextStyle(
                                            fontSize:
                                                widget.entity.contentFontSize ??
                                                    KqPadThemeManager.instance
                                                        .getConfig()
                                                        .formConfig
                                                        .contentFontSize ??
                                                    7.dm,
                                            color: KqPadThemeColors.text59),
                                      ),
                                    ),

                                  /// 单位
                                  Visibility(
                                    visible: widget.entity.showUnit &&
                                        widget.entity.unit.isNotNullOrEmpty,
                                    child: Container(
                                        padding: EdgeInsets.only(
                                            left: widget.entity.isEditable()
                                                ? 6.dm
                                                : 6.dm,
                                            right: widget.entity.isEditable()
                                                ? 6.dm
                                                : 0),
                                        child: Text(
                                          widget.entity.unit ?? "",
                                          style: TextStyle(
                                            color: widget.entity.unitColor ??
                                                KqPadThemeColors.text59,
                                            fontSize: KqPadThemeManager.instance
                                                    .getConfig()
                                                    .formConfig
                                                    .unitFontSize ??
                                                7.dm,
                                          ),
                                        )),
                                  ),

                                  /// 自定义布局，来自实体类
                                  widget.entity.customRightView != null
                                      ? widget.entity
                                          .customRightView!(widget.entity)
                                      : Container(),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

          /// 自定义底部控件，来自实体类
          widget.entity.customBottomView != null
              ? widget.entity.customBottomView!(widget.entity)
              : Container(),

          /// 分割线
          Visibility(
              visible: !widget.entity.isEditable(),
              child: const KqPadDivider()),

          /// 分隔栏
          Visibility(
              visible: widget.entity.showDivider2,
              child: SizedBox(
                height: 5.dm,
              )),
          Visibility(
              visible: widget.entity.showDivider2, child: const KqPadDivider()),
          Visibility(
              visible: widget.entity.showDivider2,
              child: SizedBox(
                height: 5.dm,
              )),
        ],
      ),
    );
  }

  /// 画笔，用于测量
  TextPainter painter = TextPainter(textDirection: TextDirection.ltr);

  /// 获取文本宽度
  double measureTextWidth(String text, {TextStyle? textStyle}) {
    painter.text = TextSpan(
      text: text,
      style: textStyle,
    );

    painter.layout();
    return painter.width;
  }

  double leftTextFiledWidth(String? text) {
    double textWidth = paintWidthWithTextStyle(text);
    double minWidth =
        paintWidthWithTextStyle(KqPadIntl.currentResource.pleaseEnter);
    return max(textWidth, minWidth);
  }

  /// 计算文本宽度
  double paintWidthWithTextStyle(
    String? text,
  ) {
    final TextPainter textPainter = TextPainter(
        text: TextSpan(
            text: text.isNullOrEmpty
                ? KqPadIntl.currentResource.pleaseEnter
                : text,
            style: TextStyle(
                fontSize: widget.entity.contentFontSize ??
                    KqPadThemeManager.instance
                        .getConfig()
                        .formConfig
                        .contentFontSize)),
        maxLines: 1,
        textDirection: TextDirection.ltr)
      ..layout(minWidth: 0, maxWidth: double.infinity);
    double size = textPainter.size.width + 4.dm; // 加上4.r这个宽度，不会自动横滚
    return size;
  }

  Widget _buildMustSign() {
    if (widget.entity.titleandMustOverAll != null) {
      if (widget.entity.titleandMustOverAll!) {
        return const SizedBox();
      }
      return _buildMustWidget();
    } else if (!KqPadThemeManager.instance
        .getConfig()
        .formConfig
        .titleandMustOverAll) {
      return _buildMustWidget();
    } else {
      return const SizedBox();
    }
  }

  Widget _buildMustWidget() {
    return Container(
      alignment: Alignment.centerRight,
      width: widget.entity.paddingHorizontal ??
          KqPadThemeManager.instance.getConfig().formConfig.paddingHorizontal ??
          8.dm,
      padding: EdgeInsets.only(right: 1.dm),
      child: Text(
        "∗",
        textAlign: TextAlign.center,
        style: TextStyle(
            fontSize: KqPadThemeManager.instance
                    .getConfig()
                    .formConfig
                    .mustInputFontSize ??
                7.dm,
            color: widget.entity.mustInput
                ? KqPadThemeColors.textRed
                : widget.entity.mustInputStarColor ??
                    KqPadThemeColors.bgTransparent),
      ),
    );
  }

  Widget _buildOverAllTitle(TextStyle? titleStyle) {
    if (widget.entity.titleandMustOverAll != null) {
      if (widget.entity.titleandMustOverAll! &&
          widget.entity.title.isNotEmpty) {
        return _buildOverAllTitleWiget(titleStyle);
      } else {
        return const SizedBox();
      }
    } else if ((KqPadThemeManager.instance
            .getConfig()
            .formConfig
            .titleandMustOverAll) &&
        widget.entity.title.isNotEmpty) {
      return _buildOverAllTitleWiget(titleStyle);
    } else {
      return const SizedBox();
    }
  }

  Widget _buildOverAllTitleWiget(TextStyle? titleStyle) {
    return Expanded(
      child: RichText(
          textAlign: widget.entity.titleTextAlign,
          text: TextSpan(
              text: widget.entity.mustInput ? '* ' : '',
              children: [
                TextSpan(
                    text: widget.entity.title.fixSoftWrap() ?? '',
                    style: titleStyle),
              ],
              style: TextStyle(
                fontSize: KqPadThemeManager.instance
                        .getConfig()
                        .formConfig
                        .mustInputFontSize ??
                    7.dm,
                color: widget.entity.mustInput
                    ? KqPadThemeColors.textRed
                    : widget.entity.mustInputStarColor ??
                        KqPadThemeColors.bgTransparent,
              ))),
    );
  }

  Widget _buildTitle(TextStyle? titleStyle) {
    if (widget.entity.titleandMustOverAll != null) {
      if (!widget.entity.titleandMustOverAll! &&
          widget.entity.title.isNotEmpty) {
        return _buildTitleWiget(titleStyle);
      } else {
        return const SizedBox();
      }
    } else if ((!KqPadThemeManager.instance
            .getConfig()
            .formConfig
            .titleandMustOverAll) &&
        widget.entity.title.isNotEmpty) {
      return _buildTitleWiget(titleStyle);
    }
    return const SizedBox();
  }

  Widget _buildTitleWiget(TextStyle? titleStyle) {
    return Expanded(
        child: Text(
      widget.entity.title.fixSoftWrap() ?? '',
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
      textAlign: widget.entity.titleTextAlign,
      style: titleStyle,
    ));
  }
}
